package gnss

import (
	"dgo/goutils/gis"
	"dgo/goutils/utils"
	"fmt"
	"strings"
)

type NtripClientConnectString struct {
	User       string
	Pass       string
	Addr       string
	MountPoint string
	NMEA       string
	Conf       string
}

type NtripSvrConnConf struct {
	Pass        string
	Addr        string
	MountPoint  string
	TimeOutSecs int
}

/*
*

	ntripsvr://0000@223.75.231.176:15005/5200/Timeout
*/
func ParseNtripSvrConnectString(str string) (rval *NtripSvrConnConf) {
	cmdstr := strings.TrimPrefix(str, "ntripsvr://")

	// PASS@
	strs := strings.SplitN(cmdstr, "@", 2)
	if len(strs) != 2 {
		return nil
	}
	authstr := strs[0]
	cmdstr = strs[1]

	// IP:PORT/MOUNTPOINT/5
	strs = strings.Split(cmdstr, "/")
	if len(strs) < 2 {
		return nil
	}
	addr := strs[0]
	mp := strs[1]

	rval = &NtripSvrConnConf{}
	rval.Pass = authstr
	rval.MountPoint = mp
	rval.Addr = addr
	rval.TimeOutSecs = -1

	if len(strs) > 2 { // timeout
		rval.TimeOutSecs = utils.StrToIntDef(utils.Trim(strs[2]), -1)
	}

	return
}

/*
*

	User和Pass中不能有"/", ":"
	USER:PASS@IP:PORT/MOUNTPOINT[/NMEA][/config]
*/
func ParseNtripClientConnectString(str string) (rval NtripClientConnectString) {
	str = strings.TrimPrefix(str, "ntripclt://")
	strs := strings.SplitN(str, "/", 4)
	if len(strs) < 2 {
		return
	}
	connString := strs[0]
	{
		idx := strings.LastIndex(connString, "@")
		if idx != -1 {
			strAuth := connString[:idx]
			strs := strings.SplitN(strAuth, ":", 2)
			rval.User = strs[0]
			if len(strs) == 2 {
				rval.Pass = strs[1]
			}

			rval.Addr = connString[idx+1:]
		} else {
			rval.Addr = connString
		}
	}
	if strings.IndexByte(rval.Addr, ':') == -1 {
		rval.Addr = fmt.Sprintf("%s:2101", rval.Addr)
	}

	rval.MountPoint = strs[1]
	strConf := ""
	if len(strs) >= 3 {
		rval.NMEA = strs[2]
	}
	if len(strs) >= 4 {
		strConf, _ = utils.QueryUnescape(strs[3])
		rval.Conf = strConf
	}

	return
}

func (this *NtripClientConnectString) MakeNowNMEA() string {
	if len(this.NMEA) == 0 {
		return ""
	}
	nmea := gis.NewNMEA()
	nmea.ParseText(this.NMEA)
	nmea.DGPSAge = "2.0"
	nmea.UpdateUTCTime()
	return nmea.Encode()
}
